var express = require('express');
var router = express.Router();
const { Course, Like , User} = require('../models');
const { Op, where, Model } = require('sequelize');
const bcrypt = require('bcryptjs')

const { BadRequestError,NotFoundError } = require('../utils/errors');
const { success, failure } = require('../utils/responses');

// 查询用户详情
router.post('/', async function (req, res, next) {
    try {
        const userId = req.userId;
        const { courseId } = req.body;

        // 查询当前课程是否存在
        // const course = await getCourse(req);
        const course = await Course.findByPk(courseId);
        if (!course) {
            throw new NotFoundError(`课程不存在`)
        }

        const likeCheck = await Like.findOne({
            where: {
                courseId,
                userId
            }
        })
        if (!likeCheck) {
            await Like.create({courseId, userId})
            await course.increment('likesCount');
            success(res, '点赞成功')
        } else {
            await likeCheck.destroy();
            await course.decrement('likesCount');
            success(res, '取消成功')
        }

    } catch (error) {
        failure(res, error)
    }
});

/**
 * 
 * @param {*} req 请求参数，中间件会返回
 * @param {*} showPassword 是否实现密码
 * @returns 查询当前用户
 */
async function getCourse(req) {
    const { courseId } = req.body;
    const course = await Course.findByPk(courseId);
    if (!course) {
        throw new NotFoundError(`课程不存在`)
    }
    return course
}

router.get('/', async function (req,res) {
    try {
        // const course = await Course.findByPk(1, {
        //     include: {
        //         model: User,
        //         as: 'likeUsers'
        //     }
        // });
        // success(res,'查询当前课程点赞的用户，成功',course)

        // const user = await User.findByPk(7, {
        //     include: {
        //         model: Course,
        //         as: 'likeCourses'
        //     }
        // });
        // success(res,'查询当前用户对哪些课程点过赞',user)

        const query = req.query;
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            // joinTableAttributes: [],
            attributes: {exclude: ['CategoryId','UserId','content']},
            order: [['id', 'DESC']],
            offset: offset,
            limit: pageSize,
        }
        console.log('req.userId->',req.userId)
        const user = await User.findByPk(req.userId);

        const courses = await user.getLikeCourses(condition);

        const count = await user.countLikeCourses();
        success(
            res,
            '查询用户点赞的课程成功',
            {
                courses,
                pagination: {
                    total: count,
                    currentPage,
                    pageSize
                }
            }
        )

    } catch (error) {
        failure(res, error)
    }
})


module.exports = router;